package com.yiwei.ydd.activity;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps2d.AMap;
import com.amap.api.maps2d.CameraUpdateFactory;
import com.amap.api.maps2d.LocationSource;
import com.amap.api.maps2d.MapView;
import com.amap.api.maps2d.model.BitmapDescriptorFactory;
import com.amap.api.maps2d.model.LatLng;
import com.amap.api.maps2d.model.Marker;
import com.amap.api.maps2d.model.MarkerOptions;
import com.amap.api.maps2d.model.MyLocationStyle;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.amap.api.services.poisearch.PoiResult;
import com.amap.api.services.poisearch.PoiSearch;
import com.yiwei.ydd.R;
import com.yiwei.ydd.base.BaseActivity;
import com.yiwei.ydd.util.PackageManagerUtil;
import com.yiwei.ydd.util.ToastUtil;
import com.yiwei.ydd.view.V19FrameLayout;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * Created by xsooy-pc on 17-12-8.
 */

public class AMapActivity extends BaseActivity implements LocationSource, AMapLocationListener, PoiSearch.OnPoiSearchListener {
    @BindView(R.id.btn_back)
    ImageView btnBack;
    @BindView(R.id.txt_title)
    TextView txtTitle;
    @BindView(R.id.txt_right)
    TextView txtRight;
    @BindView(R.id.layout_title)
    V19FrameLayout layoutTitle;
    @BindView(R.id.mapview)
    MapView mMapView;
    @BindView(R.id.txt_address)
    TextView txtAddress;
    @BindView(R.id.btn_go)
    LinearLayout btnGo;
    @BindView(R.id.layout_address)
    LinearLayout layoutAddress;
    @BindView(R.id.img_oil_type)
    ImageView imgOilType;

    private Unbinder unbiner;
    private AMap aMap;
    OnLocationChangedListener mListener;
    AMapLocationClient mlocationClient;
    AMapLocationClientOption mLocationOption;
    private double latPoi;
    private double longPoi;
    private String titlePoi;
    private double nowLongPoi;
    private double nowLatPoi;
    private Bitmap bitmapShiyou;
    private Bitmap bitmapShihua;
    private Bitmap bitmapOther;
    private int type = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_amap);
        initBar();
        unbiner = ButterKnife.bind(this);
        txtTitle.setText("附近加油站");
        mMapView.onCreate(savedInstanceState);

        if (aMap == null) {
            aMap = mMapView.getMap();
        }
        init();
    }

    private void init() {

        aMap.moveCamera(CameraUpdateFactory.zoomTo(15));

        MyLocationStyle myLocationStyle;
        myLocationStyle = new MyLocationStyle();//初始化定位蓝点样式类myLocationStyle.myLocationType(MyLocationStyle.LOCATION_TYPE_LOCATION_ROTATE);//连续定位、且将视角移动到地图中心点，定位点依照设备方向旋转，并且会跟随设备移动。（1秒1次定位）如果不设置myLocationType，默认也会执行此种模式。
        myLocationStyle.interval(2000); //设置连续定位模式下的定位间隔，只在连续定位模式下生效，单次定位模式下不会生效。单位为毫秒。
        myLocationStyle.showMyLocation(true);
        aMap.setMyLocationStyle(myLocationStyle);//设置定位蓝点的Style
//aMap.getUiSettings().setMyLocationButtonEnabled(true);设置默认定位按钮是否显示，非必需设置。
        aMap.setLocationSource(this);
// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
        aMap.setMyLocationEnabled(true);
// 设置定位的类型为定位模式，有定位、跟随或地图根据面向方向旋转几种


        AMap.OnMarkerClickListener markerClickListener = new AMap.OnMarkerClickListener() {
            // marker 对象被点击时回调的接口
            // 返回 true 则表示接口已响应事件，否则返回false
            @Override
            public boolean onMarkerClick(Marker marker) {
                txtAddress.setText(marker.getTitle());
                latPoi = marker.getPosition().latitude;
                longPoi = marker.getPosition().longitude;
                titlePoi = marker.getTitle();
                layoutAddress.setVisibility(View.VISIBLE);

                if (marker.getTitle().contains("石油")) {
                    imgOilType.setImageResource(R.mipmap.img_shiyou_two_map);
                } else if (marker.getTitle().contains("石化")) {
                    imgOilType.setImageResource(R.mipmap.img_shihua_two_map);
                } else {
                    imgOilType.setImageResource(R.mipmap.img_other_two_map);
                }
                return false;
            }
        };
// 绑定 Marker 被点击事件
        aMap.setOnMarkerClickListener(markerClickListener);

        bitmapShiyou = BitmapFactory.decodeResource(getResources(), R.mipmap.img_shiyou_one_map);
        bitmapShihua = BitmapFactory.decodeResource(getResources(), R.mipmap.img_shihua_one_map);
        bitmapOther = BitmapFactory.decodeResource(getResources(), R.mipmap.img_other_one_map);
    }

    @Override
    protected void onResume() {
        super.onResume();
        mMapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView.onPause ()，暂停地图的绘制
        mMapView.onPause();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        mMapView.onDestroy();
        if (null != mlocationClient) {
            mlocationClient.onDestroy();
        }
        unbiner.unbind();
        unbiner = null;
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //在activity执行onSaveInstanceState时执行mMapView.onSaveInstanceState (outState)，保存地图当前的状态
        mMapView.onSaveInstanceState(outState);
    }


    @Override
    public void activate(OnLocationChangedListener listener) {
        mListener = listener;
        if (mlocationClient == null) {
            //初始化定位
            mlocationClient = new AMapLocationClient(this);
            //初始化定位参数
            mLocationOption = new AMapLocationClientOption();
            //设置定位回调监听
            mlocationClient.setLocationListener(this);
            //设置为高精度定位模式
            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            mLocationOption.setOnceLocation(true);
            //设置定位参数
            mlocationClient.setLocationOption(mLocationOption);
            // 此方法为每隔固定时间会发起一次定位请求，为了减少电量消耗或网络流量消耗，
            // 注意设置合适的定位时间的间隔（最小间隔支持为2000ms），并且在合适时间调用stopLocation()方法来取消定位请求
            // 在定位结束后，在合适的生命周期调用onDestroy()方法
            // 在单次定位情况下，定位无论成功与否，都无需调用stopLocation()方法移除请求，定位sdk内部会移除
            mlocationClient.startLocation();//启动定位
        }
    }

    @Override
    public void deactivate() {
        mListener = null;
        if (mlocationClient != null) {
            mlocationClient.stopLocation();
            mlocationClient.onDestroy();
        }
        mlocationClient = null;
    }

    @Override
    public void onLocationChanged(AMapLocation amapLocation) {
        if (mListener != null && amapLocation != null) {
            if (amapLocation.getErrorCode() == 0) {
                nowLatPoi = amapLocation.getLatitude();
                nowLongPoi = amapLocation.getLongitude();
                mListener.onLocationChanged(amapLocation);// 显示系统小蓝点

                PoiSearch.Query query = new PoiSearch.Query("", "加油站", "");
                query.setPageSize(20);
                PoiSearch search = new PoiSearch(this, query);
                search.setBound(new PoiSearch.SearchBound(new LatLonPoint(nowLatPoi, nowLongPoi), 10000));
                search.setOnPoiSearchListener(this);
                search.searchPOIAsyn();


            } else {
                String errText = "定位失败," + amapLocation.getErrorCode() + ": " + amapLocation.getErrorInfo();
                Log.e("AmapErr", errText);
            }
        }
    }

    private void openGaodeMapToGuide() {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        intent.addCategory(Intent.CATEGORY_DEFAULT);

//        Uri uri = Uri.parse("androidamap://route?sourceApplication=amap&slat=" + nowLatPoi + "&slon=" + nowLongPoi
//                + "&dlat=" + latPoi + "&dlon=" + longPoi + "&dname=" + titlePoi + "&dev=1&t=2");

        Uri uri = Uri.parse("androidamap://route?sourceApplication=amap"
                + "&dlat=" + latPoi + "&dlon=" + longPoi + "&dname=" + titlePoi + "&dev=1&t=2");
//        Uri uri = Uri.parse("androidamap://navi?sourceApplication=appname&poiname=" + titlePoi + "&lat=" + latPoi + "&lon=" + longPoi + "&dev=1&style=2");

        //将功能Scheme以URI的方式传入data
        intent.setData(uri);
        //启动该页面即可
        startActivity(intent);
    }


    @OnClick({R.id.btn_back, R.id.btn_go})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_back:
                finish();
                break;
            case R.id.btn_go:
                if (PackageManagerUtil.haveGaodeMap()) {
                    openGaodeMapToGuide();
                } else {
                    ToastUtil.makeText(this, "尚未安装高德地图");
                }
                break;
        }
    }


    @Override
    public void onPoiSearched(PoiResult result, int i) {
        PoiSearch.Query query = result.getQuery();
        ArrayList<PoiItem> pois = result.getPois();
        for (PoiItem poi : pois) {

            LatLonPoint point = poi.getLatLonPoint();
            LatLng latLng = new LatLng(point.getLatitude(), point.getLongitude());
            if (poi.getTitle().contains("石油")) {
                aMap.addMarker(new MarkerOptions().position(latLng).title(poi.getTitle()).snippet(poi.getSnippet())).setIcon(BitmapDescriptorFactory.fromBitmap(bitmapShiyou));
            } else if (poi.getTitle().contains("石化")) {
                aMap.addMarker(new MarkerOptions().position(latLng).title(poi.getTitle()).snippet(poi.getSnippet())).setIcon(BitmapDescriptorFactory.fromBitmap(bitmapShihua));
            } else {
                aMap.addMarker(new MarkerOptions().position(latLng).title(poi.getTitle()).snippet(poi.getSnippet())).setIcon(BitmapDescriptorFactory.fromBitmap(bitmapOther));
            }


        }
    }

    @Override
    public void onPoiItemSearched(PoiItem poiItem, int i) {

    }
}
